<template>
  <el-drawer id="competition-index-home-drawer" :model-value="modelValue" :with-header="false" :destroy-on-close="true" :close-on-click-modal="false"
    :close-on-press-escape="false" :append-to-body="true" body-class="drawer-canvas-body" class="detail-war" size="100%"
    direction="rtl" @update:model-value="handleUpdateModelValue">
    <template #default>
      <div class="flex h-full" v-loading="settingLoading">
        <!-- 左侧设置面板 -->
        <ModuleSettingsPanel v-show="!previewVisible" :active-module="activeModule" :modules="sortedModules"
          :banner-module="bannerModule" @module-add="handleModuleAdd" @module-delete="handleModuleDelete"
          @module-update="handleModuleUpdate" @banner-update="handleBannerUpdate" @banner-activate="handleBannerActivate" />

        <!-- 右侧预览面板容器 -->
        <div class="flex-1 relative">
          <!-- 草稿提示栏 - 浮动在预览区域正上方，不占据预览区域空间 -->
          <div v-if="hasDraft && mode === 'edit' && !previewVisible"
            class="absolute top-4 left-4 right-6 z-20 h-[42px] bg-blue-100 flex justify-between items-center px-4 rounded-lg shadow-sm">
            <div class="flex items-center text-sm font-normal">
              <span><img :src="TipIcon" class="w-4 h-4 mr-2" /></span>
              {{ $t('有上次编辑记录') }}
            </div>
            <div>
              <el-button type="primary" link @click="handleContinueEdit">{{ $t('编辑草稿')
              }}</el-button>
              <el-button type="primary" link @click="handleDeleteDraftFromTip">{{ $t('competition.homePage.deleteDraft')
              }}</el-button>
            </div>
          </div>

          <!-- 预览面板 -->
          <ModulePreviewPanel :modules="sortedModules" :banner-module="bannerModule" :active-module="activeModule"
            :preview-mode="previewVisible" @module-activate="handleModuleActivate"
            @preview-area-click="handlePreviewAreaClick" />
        </div>
      </div>
    </template>

    <template #footer>
      <DrawerFooter :preview-visible="previewVisible" :save-draft-loading="saveDraftLoading"
        :submit-loading="submitLoading" @cancel="handleCancel" @preview="handlePreview" @save-draft="handleSaveDraft"
        @submit="handleSubmit" />
    </template>
  </el-drawer>
</template>

<script setup lang="ts">
import { ref, watch } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { $t } from '#/locales';
import ModuleSettingsPanel from './home-drawer/ModuleSettingsPanel.vue';
import ModulePreviewPanel from './home-drawer/ModulePreviewPanel.vue';
import DrawerFooter from './home-drawer/DrawerFooter.vue';
import deleteIcon from '#/assets/images/delete-icon.png';
import TipIcon from '#/assets/images/tip-icon.svg';
import { createMatchFirstPageApi, getMatchFirstPageApi, deleteMatchFirstPageByIdApi, getMatchFirstPageByIdApi } from '#/api/competition/competition-list';
import { useModuleManager } from './home-drawer/composables/useModuleManager';

defineOptions({ name: 'CompetitionIndexHomeDrawer' });

const emit = defineEmits(['update:modelValue', 'success', 'cancel']);

const props = defineProps({
  modelValue: { type: Boolean, default: false },
  mode: { type: String as () => 'add' | 'edit', default: 'add' },
  formData: { type: Object, default: () => ({}) },
});

// 使用模块管理 composable
const {
  modules,
  sortedModules,
  bannerModule,
  activeModule,
  previewVisible,
  settingLoading,
  submitLoading,
  saveDraftLoading,
  handleModuleAdd,
  handleModuleDelete,
  handleModuleUpdate,
  handleBannerUpdate,
  handleBannerActivate,
  handleModuleActivate,
  handlePreviewAreaClick,
  handlePreview,
  getCurrentStateJson,
  validateRequiredFields,
  buildConfigData,
  restoreModulesFromConfig,
  initializeBannerModule,
  processConfigDataForSave,
  processConfigDataForLoad,
} = useModuleManager();

const indexId = ref(''); //首页id
const lastEditId = ref(''); //草稿id
const hasDraft = ref(false); // 是否有草稿
const draftData = ref<any>(null); // 草稿数据

const handleUpdateModelValue = (v: boolean) => emit('update:modelValue', v);
const originalState = ref('');

const hasDataChanged = () => {
  return originalState.value !== getCurrentStateJson();
};

const handleCancel = () => {
  if (previewVisible.value) {
    previewVisible.value = false;
  } else {
    if (hasDataChanged()) {
      ElMessageBox.confirm('', {
        title: '',
        message: `
          <div style="display: flex; align-items: center;">
            <img src="${deleteIcon}" style="width: 48px; height: 48px; margin-right: 10px;" />
            <span>${$t('competition.homePage.pageModifiedSaveDraft')}</span>
          </div>
        `,
        confirmButtonText: $t('competition.homePage.save'),
        cancelButtonText: $t('competition.homePage.noSave'),
        customClass: 'delete-dialog',
        dangerouslyUseHTMLString: true,
        center: false,
        distinguishCancelAndClose: true,
        beforeClose: (action, instance, done) => {
          if (action === 'confirm') {
            instance.confirmButtonLoading = true;
            handleSaveDraft().then(() => {
              instance.confirmButtonLoading = false;
              done();
              emit('cancel');
            }).catch(() => {
              instance.confirmButtonLoading = false;
            });
          } else {
            done();
            emit('cancel');
          }
        },
      });
    } else {
      emit('cancel');
    }
  }
};

const handleSaveDraft = async () => {
  const matchId = props.formData?.id || '';
  if (!matchId) {
    ElMessage.error($t('competition.homePage.competitionIdRequired'));
    return;
  }

  saveDraftLoading.value = true;
  try {
    // 获取配置数据并转换图片URL为key
    const configData = buildConfigData();
    const processedConfigData = await processConfigDataForSave(configData);

    const requestData = {
      id: indexId.value || null,
      matchId: props.formData?.id,
      configTemplate: JSON.stringify(processedConfigData),
      status: 0, // 保存草稿
    };
    const response = await createMatchFirstPageApi(requestData);
    ElMessage.success($t('competition.homePage.draftSaveSuccess'));
    originalState.value = getCurrentStateJson();
    emit('success', response);
    return response;
  } finally {
    saveDraftLoading.value = false;
  }
};

const handleSubmit = async () => {
  if (!validateRequiredFields()) return;

  const matchId = props.formData?.id || props.formData?.matchId || '';
  if (!matchId) {
    ElMessage.error($t('competition.homePage.competitionIdRequired'));
    return;
  }

  submitLoading.value = true;
  try {
    // 获取配置数据并转换图片URL为key
    const configData = buildConfigData();
    const processedConfigData = await processConfigDataForSave(configData);
    const requestData = {
      id: indexId.value || null,
      matchId: matchId,
      configTemplate: JSON.stringify(processedConfigData),
      status: 1, // 保存正式信息
    };

    const response = await createMatchFirstPageApi(requestData);
    ElMessage.success($t('competition.homePage.homePageConfigSaveSuccess'));
    originalState.value = getCurrentStateJson();
    emit('success', response);
  } finally {
    submitLoading.value = false;
  }
};

// 继续编辑草稿
const handleContinueEdit = async () => {
  if (!draftData.value) return;

  hasDraft.value = false;

  // 恢复草稿数据
  try {
    const existingConfig = draftData.value;

    // 恢复配置数据（草稿数据已经在加载时转换过了）
    restoreModulesFromConfig(existingConfig);

    // 更新原始状态
    originalState.value = getCurrentStateJson();
    indexId.value = lastEditId.value;
    ElMessage.success($t('competition.homePage.draftDataLoaded'));
  } catch (error) {
    // console.error($t('competition.homePage.loadDraftDataFailed'), error);
    ElMessage.error($t('competition.homePage.loadDraftDataFailed'));
  }
};

// 从提示框删除草稿
const handleDeleteDraftFromTip = async () => {
  if (!lastEditId.value) {
    ElMessage.error($t('competition.homePage.draftIdRequired'));
    return;
  }
  // console.log('lastEditId', lastEditId.value);

  try {
    await ElMessageBox.confirm('', {
      title: '',
      message: `
        <div style="display: flex; align-items: center;">
          <img src="${deleteIcon}" style="width: 48px; height: 48px; margin-right: 10px;" />
          <span>${$t('competition.homePage.draftDeleteConfirm')}</span>
        </div>
      `,
      confirmButtonText: $t('competition.yes'),
      cancelButtonText: $t('competition.no'),
      customClass: 'delete-dialog',
      dangerouslyUseHTMLString: true,
      center: false,
      distinguishCancelAndClose: true,
      beforeClose: (action, instance, done) => {
        if (action === 'confirm') {
          instance.confirmButtonLoading = true;
          deleteMatchFirstPageByIdApi(lastEditId.value).then(() => {
            ElMessage.success($t('competition.homePage.deleteSuccess'));
            hasDraft.value = false;
            draftData.value = null;
            done();
            // 更新列表
            // emit('') 
          }).catch(() => {
            instance.confirmButtonLoading = false;
          });
        } else {
          done();
        }
      },
    });
  } catch (error) {
    if (error !== 'cancel') {
      console.error($t('competition.homePage.deleteDraftFailed'), error);
    }
  }
};

// 数据初始化监听
watch(
  () => ({ open: props.modelValue, data: props.formData }),
  async ({ open, data }) => {
    if (!open) return;

    previewVisible.value = false;
    settingLoading.value = true;

    try {
      // 重置数据
      modules.value = [];
      initializeBannerModule();
      hasDraft.value = false;
      draftData.value = null;

      // 如果是编辑模式
      if (props.mode === 'edit' && data?.id) {
        try {
          const response = await getMatchFirstPageApi({ matchId: data.id });
          // console.log('getMatchFirstPageApi', response);

          if (response && response.matchId) {
            // 保存首页id信息
            indexId.value = response.id;
            // 解析已有的配置数据
            const existingConfig = JSON.parse(response?.configTemplate || '{}');
            // console.log('加载已有配置:', existingConfig);
            // 转换配置数据中的图片key为URL
            const processedConfig = await processConfigDataForLoad(existingConfig);
            // 恢复配置数据
            restoreModulesFromConfig(processedConfig);
            // 检测是否有草稿数据
            if (response.lastEditId) {
              lastEditId.value = response.lastEditId;
              hasDraft.value = true;
              getMatchFirstPageByIdApi({ id: response.lastEditId }).then(async (res: any) => {
                // 解析已有的配置数据
                const templateConfig = JSON.parse(res?.configTemplate || '{}');
                // 转换草稿数据中的图片key为URL
                const processedDraftConfig = await processConfigDataForLoad(templateConfig);
                draftData.value = processedDraftConfig;
              })
            }
          } else {
          }
        } catch (error) {
          console.warn($t('competition.homePage.loadConfigFailed'), error);
        }
      }

      // 设置默认激活状态为Banner
      activeModule.value = {
        type: 'banner',
        id: 'banner_module',
        moduleData: bannerModule.value?.data
      };

      // 更新原始状态
      originalState.value = getCurrentStateJson();
    } catch (error) {
      console.error($t('competition.homePage.dataInitFailed'), error);
    } finally {
      settingLoading.value = false;
    }
  },
  { immediate: true, deep: true }
);


</script>

<style lang="scss" scoped>
:deep(.el-form--inline .el-form-item) {
  margin-right: 0px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
}

:deep(.el-color-picker),
:deep(.el-color-picker__trigger) {
  width: 20px;
  height: 20px;
  line-height: 0px;
  padding: 0px;
  // border: none;
  border-radius: 10px;
  overflow: hidden;

  span,
  i,
  svg {
    display: none;
  }
}
</style>
<style lang="scss">
/* 与认证首页配置抽屉保持一致的外观 */
#competition-index-home-drawer .drawer-canvas-body {
  padding: 0px !important;
  background-color: #EDEEF5 !important;
}

/* 确保左侧工作区宽度固定 */
#competition-index-home-drawer .left-workspace {
  flex-shrink: 0 !important;
  flex-grow: 0 !important;
  min-width: 385px !important;
  max-width: 385px !important;
  width: 385px !important;
}
</style>
